package init

import (
	"cogpt/internal/config"
	"cogpt/internal/log"
	"github.com/rs/zerolog"
	"gopkg.in/natefinch/lumberjack.v2"
	"os"
	"time"
)

func initLog() {
	logger := &lumberjack.Logger{
		Filename:   "log/cogpt.log",
		MaxSize:    50,
		MaxBackups: 15,
		MaxAge:     15,
		LocalTime:  true,
		Compress:   true,
	}
	consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.DateTime}
	multiWriter := zerolog.MultiLevelWriter(consoleWriter, logger)

	zerolog.TimestampFunc = time.Now
	log.Logger = zerolog.New(multiWriter).With().Timestamp().Logger()

	updateLogLevel("")

	log.Logger.Info().
		Str("type", "initLog").
		Msg("Initialized log")
}

func updateLogLevel(level string) {
	var logLevel string
	if level != "" {
		logLevel = level
	} else {
		logLevel = config.ConfigInstance.LogLevel
	}
	switch logLevel {
	case "debug":
		zerolog.SetGlobalLevel(zerolog.DebugLevel)
	case "info":
		zerolog.SetGlobalLevel(zerolog.InfoLevel)
	case "warn":
		zerolog.SetGlobalLevel(zerolog.WarnLevel)
	case "error":
		zerolog.SetGlobalLevel(zerolog.ErrorLevel)
	case "fatal":
		zerolog.SetGlobalLevel(zerolog.FatalLevel)
	case "panic":
		zerolog.SetGlobalLevel(zerolog.PanicLevel)
	case "no":
		zerolog.SetGlobalLevel(zerolog.NoLevel)
	case "disabled":
		zerolog.SetGlobalLevel(zerolog.Disabled)
	case "trace":
		zerolog.SetGlobalLevel(zerolog.TraceLevel)
	default:
		zerolog.SetGlobalLevel(zerolog.InfoLevel)
		config.ConfigInstance.LogLevel = "info"
	}

	log.Logger.Info().
		Str("type", "updateLogLevel").
		Msgf("Set log level to %s", config.ConfigInstance.LogLevel)
}
